import React, {PureComponent, Fragment} from 'react';
import {findDOMNode} from 'react-dom';
import moment from 'moment';
import {connect} from 'dva';
import {List, Card, Row, Radio, Input, Badge, Button, Icon, Dropdown, Menu, Avatar, Modal, Form, message, Select, Table, Popconfirm,DatePicker,Tag
} from 'antd';
import AddOrEditUser from './addOrEditUser';
import AddOrEditApply from './addOrEditApply'
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import debounce from 'lodash/debounce'
import {ellipsis} from '@/utils/utils';
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const SelectOption = Select.Option;
const {Search, TextArea} = Input;

@connect(({user_manage, loading}) => ({
  user_manage,
  loading: loading.models.user_manage,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'user_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'user_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }



  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      user_manage: {pageLoaded,scrollData},
    } = this.props;
    console.log('pageLoaded',pageLoaded)
    const table=document.querySelector('.ant-table-body')
    if(pageLoaded){
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      },0)

    }else{
      const {
        user_manage: {searchParams},
      } = this.props;
      console.log('searchParams',searchParams)
      dispatch({
        type: 'user_manage/fetch',
        payload: searchParams,
        callback:()=>{
          const {dispatch} = this.props;
          dispatch({
            type: 'user_manage/changeLoaded',
          })
        }
      });
    }

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll,150))
  }
  scroll=(e)=>{
    const {dispatch} = this.props;
    dispatch({
      type: 'user_manage/changeScroll',
      payload: {
        x:e.target.scrollLeft,
        y:e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY=()=>{
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top -50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table=document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll,300))
  }
  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'user_manage/fetch',
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }
  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'user_manage/remove',
      payload: {id},
      callback: ()=> {
        message.success('删除用户成功')
        const {
          user_manage: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };
  handleAdd = ()=> {
    const formValues = this.AddUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'user_manage/add',
      payload: {
        ...formValues,
        role_id: formValues.role_id ? formValues.role_id.key : '',
      },
      callback: function () {
        message.success('新建用户成功')
        that.setState({
          addModal: false,
        });
        const {
          user_manage: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleEdit = ()=> {
    const formValues = this.EditUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'user_manage/edit',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        role_id: formValues.role_id ? formValues.role_id.key : '',
      },
      callback: function () {
        message.success('修改用户成功')
        that.setState({
          editModal: false,
        });
        const {
          user_manage: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      user_manage: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem
          label={
          '开始日期'
        }>
          {getFieldDecorator('started_at', {initialValue: moment(searchParams.started_at)})(<DatePicker
            allowClear={false}
            style={{width:'140px'}}
            format="YYYY-MM-DD"/>)}
        </FormItem>
        <FormItem label={
          '结束日期'
        }>
          {getFieldDecorator('ended_at', {initialValue: moment(searchParams.ended_at)})(<DatePicker    style={{width:'140px'}}
                                                                                                      allowClear={false}
                                                                               format="YYYY-MM-DD"/>)}
        </FormItem>
        <FormItem label="用户名">
          {getFieldDecorator('username', {
            initialValue: searchParams.username,
          })(<Input    style={{width:'150px'}} placeholder="请输入"/>)}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search'  onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              const values = {
                ...fieldsValue,
              };
              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                username: values.username ? values.username : '',
                started_at: fieldsValue.started_at.format('YYYY-MM-DD HH:mm:ss'),
                ended_at: fieldsValue.ended_at.format('YYYY-MM-DD HH:mm:ss'),
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}}  icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            this.state.showAddBtn &&
            <Button  icon="plus" style={{marginLeft: 8}} type="primary" onClick={
              ()=> {
                this.setState({
                  addModal: true
                })
              }
            }>
              新建用户
            </Button>
          }

        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      page: 1,
      username: '',
      per_page: 30
    })
  }
  handleEditStatus = (id, status)=> {
    console.log(id, status)
    let sendStatus = 0;
    if (status === 1) {
      sendStatus = -1;
    } else {
      sendStatus = 1;
    }
    const that = this;
    this.props.dispatch({
      type: 'user_manage/editStatus',
      payload: {
        data: {
          id,
          status: sendStatus
        }
      },
      callback: function () {
        message.success('操作成功')
        that.handleSearch({
          page: that.state.page,
          username: that.state.username,
          per_page: that.state.per_page,
        })
      }
    });
  }
  handleEditApply = ()=> {
    const formValues = this.EditApplyUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'user_manage/editApply',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback: function () {
        message.success('修改成功')
        that.setState({
          applyModal: false,
        });
        that.handleSearch({
          page: that.state.page,
          per_page: that.state.per_page,
          username: that.state.username
        });
      }
    });
  }
  handleMenuClick = (e, record) => {
    const {dispatch} = this.props;
    const that = this
    switch (e.key) {
      case 'delete':
        dispatch({
          type: 'user_manage/remove',
          payload: {
            id: record.id,
          },
          callback: function () {
            message.success('删除成功')
            that.handleSearch({
              page: that.state.page,
              username: that.state.username,
              per_page: that.state.per_page,
            })
          }
        });
        break;
      case 'reset':
        dispatch({
          type: 'user_manage/resetPassword',
          payload: {
            id: record.id,
          },
          callback: function () {
            message.success('操作成功')
            that.handleSearch({
              page: that.state.page,
              username: that.state.username,
              per_page: that.state.per_page,
            })
          }
        });
        break;
      default:
        break;
    }
  };
  render() {
    const {
      user_manage: {data, loading, meta,searchParams,selectedRowKeys},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const renderMenu = (record) => (
      <Menu onClick={(e)=>this.handleMenuClick(e, record)} selectedKeys={[]}>
        {this.state.user_password_reset && (record.protection_level === 1 || record.protection_level === 3) &&
        <Menu.Item key="reset">重置密码</Menu.Item>}
        {this.state.showdelBtn && record.protection_level !== 2 && <Menu.Item key="delete">删除</Menu.Item>}
      </Menu>
    );
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        fixed:'left',
        width: 150,
        render:(val)=>{
          return ellipsis(val,150)
        }
      },
      {
        title: '角色',
        width: 150,
        dataIndex: 'role_display_name',
        render:(val)=>{
          return  <Tag color="red">{val}</Tag>
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        render(val) {
          return val === 1 ? <Fragment> <Icon type="check-circle" theme="twoTone"  className="table-icon" twoToneColor="#52c41a"/>启用</Fragment>:
            <Fragment> <Icon type="close-circle" theme="twoTone" className="table-icon" twoToneColor="#eb2f96"/>禁用</Fragment>
        },
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
      },

      {
        title: '操作',
        width: 226,
        fixed:'right',
        render: (val, record, index) =>{
          return    <Fragment>
            {
              this.state.showAddBtn &&
              <Button style={{marginRight: '8px'}} type="primary" icon='edit' size="small" onClick={(e)=> {
                e.stopPropagation()
                this.setState({
                  editRecord: record,
                  editModal: true
                })
              }
              }>编辑</Button>
            }
            {
              this.state.showAddBtn &&
              <Popconfirm title={record.status === 1 ? '确定要禁用吗?' : '确定要启用吗?'}
                          onConfirm={()=>this.handleEditStatus(record.id, record.status)}>
                <Button className={record.status === 1 ?"":"btn-green"} type={record.status === 1 ?"danger":"primary"} style={{marginRight: '8px'}} icon='edit'
                        size="small" onClick={(e)=>{ e.stopPropagation()}}>{record.status === 1 ? '禁用' : '启用' }</Button>
              </Popconfirm>
            }
            {
             this.state.showAddBtn &&this.state.showdelBtn &&
              <Dropdown overlay={renderMenu(record)}>
                <Button size="small"  onClick={(e)=>{ e.stopPropagation()}}>
                  其它 <Icon type="down"/>
                </Button>
              </Dropdown>
            }

          </Fragment>
        }
      },
    ];
    const rowSelection = {
      columnWidth:40,
      selectedRowKeys,
      columnTitle:' ',
      onChange:(selectedRowKeys) => {
        this.props.dispatch({
          type: 'user_manage/changeSelectRow',
          payload: selectedRowKeys,
        })
      },
    };
    return <div className="custom-card">
      <div className="table-title" >用户管理</div>
      <div className="table-page">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <Table
            style={{color: '#fff'}}
            className="custom-small-table"
            loading={loading}
            rowKey={'id'}
            dataSource={data}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: true, y: this.state.tableY}}
            rowSelection={rowSelection}
            onRow={(record) => ({
              onClick: () => {
                this.props.dispatch({
                  type: 'user_manage/selectRow',
                  payload: record,
                })
              },
            })}
          />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={'新建用户'}
        visible={this.state.addModal}
        centered
        onCancel={()=> {
          this.setState({addModal: false})
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddUser = inst}/>

      </Modal>
      <Modal
        title={'编辑' + this.state.editRecord.username }
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        onCancel={()=> {
          this.setState({editModal: false, editRecord: {}})
        }}
      >
        <AddOrEditUser editRecord={this.state.editRecord}
                       wrappedComponentRef={(inst) => this.EditUser = inst}/>

      </Modal>
      <Modal
        title={'审核' + this.state.editRecord.username }
        destroyOnClose
        visible={this.state.applyModal}
        centered
        onOk={this.handleEditApply}
        onCancel={()=> {
          this.setState({applyModal: false, editRecord: {}})
        }}
      >
        <AddOrEditApply
          wrappedComponentRef={(inst) => this.EditApplyUser = inst}/>

      </Modal>
    </div>
  }
}

export default BasicList;
